/**
 * 自定义表格hooks封装
 * @Author: linzy
 * @Date: 2022-05-24
 * 传参：
 *    需要传入tableForm 监听改变表格数据的对象 比如搜索、分页里面的数据放在同个tableForm中
 *    tableFormSet 监听改变表格数据的对象的set方法
 *    tableData 表格的数据对象
 *    rowKey: 默认为"id"
 *    sortChange 为排序的change事件 返回的对象格式为 {sort:xxx,order:xxx}
 *    sortMap 排序映射 sortMap: {sort: 'sortParam',order: 'sortType'},
 * @description 自定义表格hooks封装
 * @function useTable
 * @param {object} tableForm - 表格监听对象
 * @param {function} tableFormSet - 表格兼容对象设置方法
 * @param {object} tableData - 表格数据 格式为 {count: xxx,items: []}
 * @param {object[]} columns - 表格项数组
 * @param {function} sortChange - 排序回调
 * @param {object} sortMap - 排序字段对象 {sort: 'sortParam',order: 'sortType'},
 * @param {function} onChange - 表格change回调
 * @property {string} rowKey=id - 表格行rowKey
 * @property {object} scroll={x:"max-content"} - 表格滚动参数
 * @property {object} rowSelection={} - 表格多选，传入空对象{}, 会返回selectedRowKeys, selectedRows
 * @property {*} ... - antd Table组件属性
 * <caption>Table组件默认参数</caption>
 *
 * @example
 * const [tableForm, tableFormSet, push] = useTableState(props);
const tableData = {
  items: [{ id: 1 }, { id: 3, status: 2 }],
  count: 9
};
const columns = [
  { title: "发布会封面图", dataIndex: "pic", type: "preview" },
  {
    title: "直播ID", dataIndex: "id", type: "copy"
  },
  {
    title: "权重", dataIndex: "weight", type: "weight",
    onChange: function (params) {
      // btnClick('weight', params)
    }
  },
  {
    title: "状态", dataIndex: "status", type: "status",
    enum: { 1: "未开始", 2: "进行中", 3: "已结束" }
  },
  { title: "时间", dataIndex: "datetime", type: "datetime" },
  {
    title: "操作",
    buttons: [
      { title: "编辑", type: "edit" },
      {
        title: "删除", type: "delete",
        onConfirm(record, index) {
          // btnClick('delete', record, index)
        }
      },
    ]
  }
];
const [Table, tableProps, selectedRowKeys, selectedRows] = useTable({
  columns,
  loading,
  tableData,
  tableForm,
  tableFormSet,
});
<Table {...tableProps} />
 */
import { useState } from "react";
import { Table } from "antd";
import { usePagination, useColumns } from "@/hooks";
import { typeOf } from "@/hooks/tools";
import _ from "lodash";

export default props => {
  const {
    tableForm,
    tableFormSet,
    tableData = {},
    columns = [],
    sortChange,
    sortMap,
    onChange,
    paginationProps,
    ...restProps
  } = props;
  let pagination = false;
  const [selectedRowKeys, selectedRowKeysSet] = useState([]);
  const [selectedRows, selectedRowsSet] = useState([]);
  if (tableForm && tableFormSet && tableData) {
    pagination = usePagination({
      tableForm,
      tableData,
      tableFormSet,
      paginationProps
    });
  }
  let dataSource = restProps.dataSource
    ? restProps.dataSource
    : typeOf(tableData) === "object"
    ? tableData?.items ?? tableData?.list ?? []
    : typeOf(tableData) === "array"
    ? tableData
    : [];
  const tableProps = {
    rowKey: "id",
    dataSource,
    pagination,
    onChange(pagination, filters, sorter, extra) {
      onChange && onChange(pagination, filters, sorter, extra);
      const { field, order } = sorter;
      const sortObj = {};
      if (order) {
        sortObj.sort = field;
        sortObj.order = order.replace("end", "");
      } else {
        sortObj.sort = undefined;
        sortObj.order = undefined;
      }
      sortChange && sortChange(sortObj);
      if (sortMap && tableFormSet) {
        tableFormSet(state => {
          return {
            ...state,
            page: pagination.current,
            [sortMap.sort]: sortObj.sort,
            [sortMap.order]: sortObj.order
          };
        });
      }
    },
    scroll: { x: "max-content" },
    ...restProps
  };
  // 处理排序
  columns.forEach(item => {
    if (item.sorter === true && !item.onHeaderCell) {
      item.onHeaderCell = column => {
        return {
          onClick: () => {
            tableFormSet &&
              tableFormSet(state => {
                return {
                  ...state,
                  page: 1
                };
              });
          }
        };
      };
    }
  });
  columns && (tableProps.columns = useColumns(columns, tableForm));
  // 处理表格多选
  if (restProps.rowSelection) {
    tableProps.rowSelection = {
      onChange(selectedRowKeys, selectedRows) {
        selectedRowKeysSet(selectedRowKeys);
        selectedRowsSet(state => {
          const key = tableProps.rowKey;
          return _.chain([...state, ...selectedRows])
            .uniqBy(key)
            .filter(item => {
              return selectedRowKeys.includes(item[key]);
            })
            .value();
        });
      },
      fixed: true,
      selectedRowKeys: selectedRowKeys,
      ...restProps.rowSelection
    };
  }
  // 处理排序
  if (sortMap) {
    let sort = tableForm[sortMap.sort];
    let order = tableForm[sortMap.order];
    tableProps.columns.forEach(item => {
      if (item.sorter) {
        if (order) {
          if (item.dataIndex === sort) {
            item.sortOrder = order + "end";
          } else {
            item.sortOrder = false;
          }
        } else {
          item.sortOrder = false;
        }
      }
    });
  }
  return [
    Table,
    tableProps,
    selectedRowKeys,
    selectedRows,
    selectedRowKeysSet,
    selectedRowsSet
  ];
};
